//
//  UIImage+MC_RGB.m
//  RetainCount
//
//  Created by liuxiang on 2017/12/4.
//  Copyright © 2017年 liuxiang. All rights reserved.
//

#import "UIImage+MC_RGB.h"

@implementation UIImage (MC_RGB)

static CGContextRef CreateRGBABitmapContext (CGImageRef inImage)
{
    CGContextRef content = NULL;
    CGColorSpaceRef colorSpace;
    void *bitmapData;
    NSInteger bitmapByCount;
    NSInteger bitmapBytesPerRow;
    
    size_t pixelsWide = CGImageGetWidth(inImage);//获取图片横向像素点的个数
    size_t pixelsHigh = CGImageGetHeight(inImage);//纵向像素点的个数
    
    //每一行像素所占的字节数 每个像素的RGBA四个通道个占8bit(0-255)的空间
    bitmapBytesPerRow = pixelsWide*4;
    //计算整张图像素所占的字节数
    bitmapByCount = bitmapBytesPerRow*pixelsHigh;
    //分配足够的空间来存储图片的字节数
    bitmapData = malloc(bitmapByCount);
    //创建依赖于设备的RGB通道
    colorSpace = CGColorSpaceCreateDeviceRGB();
    
    content = CGBitmapContextCreate(bitmapData,
                                    pixelsWide,
                                    pixelsHigh,
                                    8,
                                    bitmapBytesPerRow,
                                    colorSpace,
                                    kCGBitmapByteOrderDefault|kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorSpace);
    free(bitmapData);
    return content;
}

// 返回一个指针，该指针指向一个数组，数组中的每四个元素都是图像上的一个像素点的RGBA的数值(0-255)，用无符号的char是因为它正好的取值范围就是0-255
static unsigned char *RequestImagePixelData(UIImage *inImage)
{
    CGImageRef img = [inImage CGImage];
    CGSize size = [inImage size];
    //使用上面的函数创建上下文
    CGContextRef cgctx = CreateRGBABitmapContext(img);
    
    CGRect rect = {{0,0},{size.width, size.height}};
    //将目标图像绘制到指定的上下文，实际为上下文内的bitmapData。
    CGContextDrawImage(cgctx, rect, img);
    unsigned char *data = CGBitmapContextGetData (cgctx);
    //释放上面的函数创建的上下文
    CGContextRelease(cgctx);
    return data;
}

+ (unsigned char *)mc_private_getRGBFromImage:(UIImage *)image
{
    return RequestImagePixelData(image);
}


+ (UIImage *) convertBitmapRGBA8ToUIImage:(unsigned char *) buffer
                                withWidth:(int) width
                               withHeight:(int) height {
    
    
    size_t bufferLength = width * height * 4;
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, bufferLength, NULL);
    size_t bitsPerComponent = 8;
    size_t bitsPerPixel = 32;
    size_t bytesPerRow = 4 * width;
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    if(colorSpaceRef == NULL) {
        NSLog(@"Error allocating color space");
        CGDataProviderRelease(provider);
        return nil;
    }
    
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    
    CGImageRef iref = CGImageCreate(width,
                                    height,
                                    bitsPerComponent,
                                    bitsPerPixel,
                                    bytesPerRow,
                                    colorSpaceRef,
                                    bitmapInfo,
                                    provider,    // data provider
                                    NULL,        // decode
                                    YES,            // should interpolate
                                    renderingIntent);
    
    uint32_t* pixels = (uint32_t*)malloc(bufferLength);
    
    if(pixels == NULL) {
        NSLog(@"Error: Memory not allocated for bitmap");
        CGDataProviderRelease(provider);
        CGColorSpaceRelease(colorSpaceRef);
        CGImageRelease(iref);
        return nil;
    }
    
    CGContextRef context = CGBitmapContextCreate(pixels,
                                                 width,
                                                 height,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpaceRef,
                                                 kCGImageAlphaPremultipliedLast);
    
    if(context == NULL) {
        NSLog(@"Error context not created");
        free(pixels);
    }
    
    UIImage *image = nil;
    if(context) {
        
        CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), iref);
        
        CGImageRef imageRef = CGBitmapContextCreateImage(context);
        
        // Support both iPad 3.2 and iPhone 4 Retina displays with the correct scale
        if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
            float scale = [[UIScreen mainScreen] scale];
            image = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
        } else {
            image = [UIImage imageWithCGImage:imageRef];
        }
        
        CGImageRelease(imageRef);
        CGContextRelease(context);
    }
    
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(iref);
    CGDataProviderRelease(provider);
    
    if(pixels) {
        free(pixels);
    }
    return image;
}


+ (UIImage *) mc_createBackgroundImageFromImage:(UIImage *)image {
    UIImage *resultImage = nil;
    unsigned char *imgPixel = [self mc_private_getRGBFromImage:image];
    int wdith = image.size.width;
    int height = image.size.height;
    for (int i = 0; i < wdith*height*4; i +=4) {
        double r = (unsigned char)imgPixel[i];
        double g = (unsigned char)imgPixel[i+1];
        double b = (unsigned char)imgPixel[i+2];
        double a = (unsigned char)imgPixel[i+3];
        if (i <= 100) {
            NSLog(@"r= %d\ng = %d\nb = %d\na = %d",r,g,b,a);
        }
        

    }
    
  
    
    return resultImage;
}

@end
